<!DOCTYPE html>
<html lang="zh-Hans">
  <head hexo-theme='https://github.com/volantis-x/hexo-theme-volantis/tree/4.3.1'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta http-equiv='x-dns-prefetch-control' content='on' />
  <link rel='dns-prefetch' href='https://cdn.jsdelivr.net'>
  <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <link rel="preload" href="/android-note/css/first.css" as="style">
  

  <!-- 页面元数据 -->
  
  <title>Android 开发总结笔记(五) - Java 线程总结 - Xander&#39;s blog</title>
  
    <meta name="keywords" content="Android,线程">
  

  

  <!-- feed -->
  

  <!-- import meta -->
  

  <!-- link -->
  

  <!-- import link -->
  
  
  <link rel="shortcut icon" href="/android-note/images/xander_blog.ico">
  

  
    
<link rel="stylesheet" href="/android-note/css/first.css">

  

  
  <link rel="stylesheet" href="/android-note/css/style.css" media="print" onload="this.media='all';this.onload=null">
  <noscript><link rel="stylesheet" href="/android-note/css/style.css"></noscript>
  

  <script id="loadcss"></script>

  
<script>
if (/*@cc_on!@*/false || (!!window.MSInputMethodContext && !!document.documentMode))
    document.write(
	'<style>'+
		'html{'+
			'overflow-x: hidden !important;'+
			'overflow-y: hidden !important;'+
		'}'+
		'.kill-ie{'+
			'text-align:center;'+
			'height: 100%;'+
			'margin-top: 15%;'+
			'margin-bottom: 5500%;'+
		'}'+
	'</style>'+
    '<div class="kill-ie">'+
        '<h1><b>抱歉，您的浏览器无法访问本站</b></h1>'+
        '<h3>微软已经于2016年终止了对 Internet Explorer (IE) 10 及更早版本的支持，<br/>'+
        '继续使用存在极大的安全隐患，请使用当代主流的浏览器进行访问。</h3><br/>'+
        '<a target="_blank" rel="noopener" href="https://www.microsoft.com/zh-cn/WindowsForBusiness/End-of-IE-support"><strong>了解详情 ></strong></a>'+
    '</div>');
</script>


<noscript>
	<style>
		html{
			overflow-x: hidden !important;
			overflow-y: hidden !important;
		}
		.kill-noscript{
			text-align:center;
			height: 100%;
			margin-top: 15%;
			margin-bottom: 5500%;
		}
	</style>
    <div class="kill-noscript">
        <h1><b>抱歉，您的浏览器无法访问本站</b></h1>
        <h3>本页面需要浏览器支持（启用）JavaScript</h3><br/>
        <a target="_blank" rel="noopener" href="https://www.baidu.com/s?wd=启用JavaScript"><strong>了解详情 ></strong></a>
    </div>
</noscript>

</head>

  <body>
    

<header id="l_header" class="l_header auto shadow blur show" style='opacity: 0' >
  <div class='container'>
  <div id='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h m-phone' id="pjax-header-nav-list">
        <li><a id="s-comment" class="fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a id="s-toc" class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/android-note/'>
          
            <img no-lazy class='logo' src='https://i.loli.net/2020/05/18/WO1oJwFsRb4gV79.png'/>
          
          
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h m-pc'>
          
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/
                  
                  
                  
                    id="android-note"
                  >
                  <i class='fas fa-book fa-fw'></i>BLOG
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/categories/
                  
                  
                  
                    id="android-notecategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/tags/
                  
                  
                  
                    id="android-notetags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/archives/
                  
                  
                  
                    id="android-notearchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/about/
                  
                  
                  
                    id="android-noteabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box header toggle-mode-btn">
                  <i class='fas fa-moon fa-fw'></i>暗黑模式
                </a>
              <li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="Search..." />
        </form>
      </div>

			<ul class='switcher nav-list-h m-phone'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/
                  
                  
                  
                    id="android-note"
                  >
                  <i class='fas fa-book fa-fw'></i>BLOG
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/categories/
                  
                  
                  
                    id="android-notecategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/tags/
                  
                  
                  
                    id="android-notetags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/archives/
                  
                  
                  
                    id="android-notearchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/android-note/about/
                  
                  
                  
                    id="android-noteabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box header toggle-mode-btn">
                  <i class='fas fa-moon fa-fw'></i>暗黑模式
                </a>
              <li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

    <div id="l_body">
      <div id="l_cover">
  
    
        <div id="full" class='cover-wrapper post dock' style="display: none;">
          
            <div id='cover-backstretch'></div>
          
          <div class='cover-body'>
  <div class='top'>
    
    
      <p class="title">Xander's Blog</p>
    
    
      <p class="subtitle">A blog for Android</p>
    
  </div>
  <div class='bottom'>
    <div class='menu navigation'>
      <div class='list-h'>
        
          
            <a href="/android-note/"
              
              
              id="android-note">
              <i class='fas fa-book fa-fw'></i><p>BLOG</p>
            </a>
          
            <a href="/android-note/categories/"
              
              
              id="android-notecategories">
              <i class='fas fa-folder-open fa-fw'></i><p>分类</p>
            </a>
          
            <a href="/android-note/tags/"
              
              
              id="android-notetags">
              <i class='fas fa-tags fa-fw'></i><p>标签</p>
            </a>
          
            <a href="/android-note/archives/"
              
              
              id="android-notearchives">
              <i class='fas fa-archive fa-fw'></i><p>归档</p>
            </a>
          
            <a href="/android-note/about/"
              
              
              id="android-noteabout">
              <i class='fas fa-info-circle fa-fw'></i><p>关于</p>
            </a>
          
        
      </div>
    </div>
  </div>
</div>

          <div id="scroll-down" style="display: none;"><i class="fa fa-chevron-down scroll-down-effects"></i></div>
        </div>
    
  
  </div>

      <div id="safearea">
        <div class="body-wrapper" id="pjax-container">
          

<div class='l_main'>
  <article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost">
  


  
  <div class="article-meta" id="top">
    
    
    
      <h1 class="title">
        Android 开发总结笔记(五) - Java 线程总结
      </h1>
      <div class='new-meta-box'>
        
          
            
<div class='new-meta-item author'>
  <a class='author' target="_blank" href="https://github.com/XanderWang/" rel="nofollow noopener">
    <img no-lazy src="https://i.loli.net/2020/05/18/WO1oJwFsRb4gV79.png">
    <p>XanderWang</p>
  </a>
</div>

          
        
          
            
  <div class='new-meta-item category'>
    <a class='notlink'>
      <i class="fas fa-folder-open fa-fw" aria-hidden="true"></i>
      <a class="category-link" href="/android-note/categories/Android-%E6%80%BB%E7%BB%93/">Android 总结</a>
    </a>
  </div>


          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：Feb 26, 2021</p>
  </a>
</div>

          
        
          
            
  <div class="new-meta-item browse leancloud">
    <a class='notlink'>
      
      <div id="lc-pv" data-title="Android 开发总结笔记(五) - Java 线程总结" data-path="/android-note/2021/02/26/android_note/android_note_05/">
        <i class="fas fa-eye fa-fw" aria-hidden="true"></i>
        <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
        次浏览
      </div>
    </a>
  </div>


          
        
      </div>
    
  </div>


  
  
  <h1 id="Java-线程总结"><a href="#Java-线程总结" class="headerlink" title="Java 线程总结"></a>Java 线程总结</h1><h2 id="Java-线程安全"><a href="#Java-线程安全" class="headerlink" title="Java 线程安全"></a>Java 线程安全</h2><h3 id="什么是线程安全"><a href="#什么是线程安全" class="headerlink" title="什么是线程安全"></a>什么是线程安全</h3><p>在上一节的 Java 内存模型里面说到，程序在运行的时候，线程并不是直接从主存里面，而是先从主内存拷贝一份到工作内存(线程私有的)，然后执行代码，最后把计算结果从工作内存写回到主内存。</p>
<p>有个小问题，为是么需要 JMM ？</p>
<p>cpu 在存取数据或者存取指令的时候，如果都是在一片连续的区域，效率会高，所以栈里面会有一个变量的副本，这样会把需要参与计算的变量放到一片连续的区域，会提高执行效率，但是这样就会有一个数一致性问题，也就是线程安全问题。说到底就是数据同步问题。</p>
<p>当有多个线程同时访问同一个变量的时候，因为线程在运算的时候，可能并不是拿的“最新”的值来参与计算的，或者说，参与计算的值不是“最新的”，因为其他线程更新了这个变量，但是线程不知道，还是用的“旧的值”。最终，执行完代码后，写回到主存的值是不符合预期的值。这种情况就是线程不安全，所以，对应的，线程安全就是多个线程同时访问同一个变量的时候，最终的结果和预期结果一致，就表明是线程安全的。</p>
<p>线程要保证安全，需要满足三个条件</p>
<ul>
<li>原子性(Synchronized / Lock)</li>
</ul>
<p>原子性的意思是，某个操作要么执行完，要么不做。比如读取值，执行时，开始读数据了，需要保证不能被打断。要么不读值。</p>
<ul>
<li>可见性(Volatile / Synchronized / Lock)</li>
</ul>
<p>可见性的意思是对值得读写可以立刻捕获，就是说某个线程可以“观察”到其他线程对值得修改，同时，这个线程对值的修改，其他线程也可以“观察”到。</p>
<ul>
<li>有序性(Volatile / Synchronized / Lock)</li>
</ul>
<p>说到有序性需要说到指令重排，指令重排是为了提高 CPU 的指令执行效率，执行代码的时候，会把一些源码上的不影响方法执行结果的代码打乱执行，以提高 CPU 执行效率。有序性的意思就是说最终代码编译的指令是按照代码的书写顺序执行的。</p>
<h3 id="Volatile"><a href="#Volatile" class="headerlink" title="Volatile"></a>Volatile</h3><p>上面说到了，线程安全在于没有“及时”读取到最新的值。要想“及时”读取到最新的值，我们需要用到 volatile 关键字，我们先看看值是如何读取的。</p>
<h4 id="Java-变量的读写"><a href="#Java-变量的读写" class="headerlink" title="Java 变量的读写"></a>Java 变量的读写</h4><p>Java 变量读的读写是以下的指令来完成的，通过以下的指令，把变量的值从主内存读取到工作内存，工作内存变化后，写入主内存。</p>
<table>
<thead>
<tr>
<th>指令</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>lock</td>
<td>作用于主内存，把变量标识为线程独占状态。</td>
</tr>
<tr>
<td>unlock</td>
<td>作用于主内存，解除独占状态。</td>
</tr>
<tr>
<td>read</td>
<td>作用主内存，把一个变量的值从主内存传输到线程的工作内存。</td>
</tr>
<tr>
<td>load</td>
<td>作用于工作内存，把 read 操作传过来的变量值放入工作内存的变量副本中。</td>
</tr>
<tr>
<td>use</td>
<td>作用工作内存，把工作内存当中的一个变量值传给执行引擎。</td>
</tr>
<tr>
<td>assign</td>
<td>作用工作内存，把一个从执行引擎接收到的值赋值给工作内存的变量。</td>
</tr>
<tr>
<td>store</td>
<td>作用于工作内存的变量，把工作内存的一个变量的值传送到主内存中。</td>
</tr>
<tr>
<td>write</td>
<td>作用于主内存的变量，把 store 操作传来的变量的值放入主内存的变量中。</td>
</tr>
</tbody></table>
<h4 id="volatile-如何保持内存可见性"><a href="#volatile-如何保持内存可见性" class="headerlink" title="volatile 如何保持内存可见性"></a>volatile 如何保持内存可见性</h4><ul>
<li>read、load、use 动作必须连续出现。</li>
<li>assign、store、write 动作必须连续出现。</li>
</ul>
<p>所以，使用 volatile 变量能够保证:</p>
<ul>
<li>每次<code>读取前</code>必须先从主内存刷新最新的值。</li>
<li>每次<code>写入后</code>必须立即同步回主内存当中。</li>
</ul>
<p>有了这 2 条规则，线程就可以及时“观察”到变量值得变化了。</p>
<h4 id="volatile-如何防止指令重排序"><a href="#volatile-如何防止指令重排序" class="headerlink" title="volatile 如何防止指令重排序"></a>volatile 如何防止指令重排序</h4><p>通过内存屏障来实现的。</p>
<table>
<thead>
<tr>
<th>屏障</th>
<th>举例</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>LoadLoad</td>
<td>Load1;LoadLoad;Load2</td>
<td>Load2 以及之后的读操作要在 Load1 完成之后</td>
</tr>
<tr>
<td>LoadStore</td>
<td>Load1;LoadStore;Store</td>
<td>Store2 以及之后的写操作要在 Load1 完成之后</td>
</tr>
<tr>
<td>StoreStore</td>
<td>Store1;StoreStore;Store2</td>
<td>Store2 以及之后的写操作要在 Store1 完成之后</td>
</tr>
<tr>
<td>StoreLoad</td>
<td>Store1;StoreLoad;Load2</td>
<td>Load2  以及之后的读操作需要在 Store1 完成之后</td>
</tr>
</tbody></table>
<p>为了实现volatile的内存语义，编译器在生成字节码时，会在指令序列中插入内存屏障来禁止特定类型的处理器重排序。然而，对于编译器来说，发现一个最优布置来最小化插入屏障的总数几乎不可能，为此，Java内存模型采取保守策略。</p>
<p>下面是基于保守策略的JMM内存屏障插入策略：</p>
<ul>
<li>在每个 volatile 写操作的前面插入一个 StoreStore 屏障。</li>
<li>在每个 volatile 写操作的后面插入一个 StoreLoad 屏障。</li>
<li>在每个 volatile 读操作的后面插入一个 LoadLoad 屏障。</li>
<li>在每个 volatile 读操作的后面插入一个 LoadStore 屏障。</li>
</ul>
<p><a target="_blank" rel="noopener" href="https://monkeysayhi.github.io/2016/11/29/volatile%E5%85%B3%E9%94%AE%E5%AD%97%E7%9A%84%E4%BD%9C%E7%94%A8%E3%80%81%E5%8E%9F%E7%90%86/">volatile关键字的作用、原理</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/zhengbin/p/6407137.html">Java内存模型</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/chenyangyao/p/5269622.html">JVM内存模型、指令重排、内存屏障概念解析</a></p>
<p>解决这个问题(线程不安全)的办法有以下几种方式</p>
<ol>
<li>synchronized</li>
<li>Lock + volatile</li>
</ol>
<p>说到底，线程安全的主要的思想就是利用某种方式，保证同时只有一个线程在使用这个变量或者说是方法块，其他的线程“阻塞”，等待正在执行的线程执行完。线程油冰雪执行变成串行执行。</p>
<h3 id="线程安全的实现方式"><a href="#线程安全的实现方式" class="headerlink" title="线程安全的实现方式"></a>线程安全的实现方式</h3><h4 id="synchronized"><a href="#synchronized" class="headerlink" title="synchronized"></a>synchronized</h4><p>synchronized 通过字节码指令 enterMoniter 和 exitMoniter 实现同时只有一个线程可以执行某段代码块，等这段代码块执行完以后，其他的线程才可以执行。</p>
<p>这里面需要了解 synchronized 的作用对象，作用对象是一个 Object 。</p>
<p>大概的原理就是:每个对象都有一个对象头，这个对象头里面存储了相应的锁的信息(无锁、偏向锁、轻量锁和重量锁)。当代码执行到 synchronized 代码的时候，会看这个锁作用的对象的对象头，是有锁还是无锁，无锁就加锁后继续执行。有锁后就阻塞，等待其他线程执行完。</p>
<p>但是一开始 synchronized 是一个比较重的操作，后续做了优化，这些优化分别是自旋锁、轻量锁、偏向锁。</p>
<p>自旋就是不会立即 block 线程，而是做一段小的自循环，如果还是无法获取锁，再 block 线程。</p>
<p>轻量锁是指，虽然对于同一段代码，有多个线程竞争，但是竞争发生在不同的时间段。轻量锁的做法是第一次对锁对象加锁的时候，锁对象的对象头记录指向线程中的锁记录。再次执行代码，加锁锁对象的时候，如果锁对象的对象头指向的锁记录是这个线程，就直接执行，跳过加锁过程。</p>
<p>偏向锁就是，锁对象被加锁的时候，锁对象的对象头会保存持有锁的线程 id , 当同步代码执行完后，再次对锁对象加锁的时候，如果锁对象的对象头是偏向锁，并且 thread id 是当前线程，那么就不做加锁过程，直接执行。</p>
<p>轻量级锁和偏向锁如果存在竞争，最终还是会膨胀为重量锁的。</p>
<h4 id="锁膨胀过程"><a href="#锁膨胀过程" class="headerlink" title="锁膨胀过程"></a>锁膨胀过程</h4><p>偏向锁(01)：做一次 cas 操作，如果成功，说明获取偏向锁成功，对象头记录获取锁的 ThreadId ，如果失败，说明有竞争，这个时候需要膨胀为轻量级锁。</p>
<p>轻量级锁(00)：某个线程获取锁的时候，如果对象头是偏向锁，就看 ThreadId 对应的线程是否还活着，如果活着，就看是否退出同步块，如果不存活或者已经退出同步块，就尝试 cas 操作获取偏向锁，如果 cas 失败，说明有竞争，这个时候需要由偏向锁膨胀为轻量级锁，具体的过程就是 JVM 会把当前获取锁的线程挂起，然后再线程的当前栈帧里面创建一个锁记录，然后把对象头用 CAS 拷贝进去，同时创建一个 Owner 指针指向锁对象的对象头，然后锁对象的对象头指向这个锁记录，然后之前获取锁的线程继续执行，没有获取到锁的线程先自旋一段时间，如果自旋结束后成功获取到轻量级锁，就继续执行，如果自旋后还是获取不到轻量级锁，说明由更严重(多个线程)的竞争，需要膨胀为重量级锁。</p>
<p>重量级锁(10)：线程</p>
<p>参考资料：</p>
<p><a target="_blank" rel="noopener" href="https://juejin.im/post/5ca766dcf265da30d02fb35c">https://juejin.im/post/5ca766dcf265da30d02fb35c</a></p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/dsj2016/p/5714921.html">JAVA锁的膨胀过程和优化</a></p>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/133319319">聊聊Java 锁的JVM锁</a></p>
<p><a target="_blank" rel="noopener" href="https://xinghelanchen.github.io/2018/08/22/JAVA%E9%94%81%E7%9A%84%E8%86%A8%E8%83%80%E8%BF%87%E7%A8%8B%E5%92%8C%E4%BC%98%E5%8C%96/">JAVA锁的膨胀过程和优化</a></p>
<h4 id="Lock-volatile"><a href="#Lock-volatile" class="headerlink" title="Lock + volatile"></a>Lock + volatile</h4><p>lock 的话主要是利用 AQS 框架来实现的同步机制。</p>
<p>AQS 框架内部利用了 CAS 来判断是否有线程持有锁。当有其他线程持有锁的时候，会 block 当前线程，然后入队列(入队的时候可能会有自旋)，当持有锁的线程释放锁后，会唤醒 block 的线程。</p>
<p>CAS 是 Java 提供的原子性操作 API 。</p>
<p>AQS 框架的理解：</p>
<pre><code class="java">acquire 独占式获取锁，如果没有获取成功，就入队列并阻塞。

tryAcquire 独占式锁子类需要复写的方法，独占式请求锁。返回 true 表示线程获取锁成功，false 表示获取锁失败。

acquireShare 共享式获取锁，当获取锁的线程数量超过指定数量(tryAcquireShare的返回结果小于0)，就阻塞尝试获取锁的线程。

tryAcquireShare 共享式锁子类需要复写的方法。返回值如果小于 0 表示共享锁的数量消耗完，需要阻塞。

acquireQueued 独占的时候，入队列
addWaiter  具体的入队列入口
doAcquireShared 共享的时候，入队列
</code></pre>
<h3 id="Java-里锁的分类"><a href="#Java-里锁的分类" class="headerlink" title="Java 里锁的分类"></a>Java 里锁的分类</h3><ul>
<li>公平/非公平锁</li>
</ul>
<p>公平：按照请求锁的时间顺序依次获取锁，非公平锁就是不一定是按照请求锁的时间顺序来获取锁的。</p>
<ul>
<li>独占/共享锁</li>
</ul>
<p>独占锁(ReentrantLock)就是锁只能同时被一个线程持有，共享锁(CountDownLatch/Semaphone)就是锁可以同时被多个线程持有。</p>
<ul>
<li>自旋锁</li>
</ul>
<p>没有请求到锁的时候，做一段循环，等待持有锁的线程释放锁，然后请求锁。坏处就是，如果自旋过久，也会消耗大量的 cpu 资源。</p>
<ul>
<li>偏向锁/轻量锁/重量锁</li>
</ul>
<p>synchornized 的优化，如果再偏向锁发生竞争的时候会锁膨胀</p>
<ul>
<li>可重入/不可重入</li>
</ul>
<p>线程获取某个锁后，再次请求这个锁，仍然可以获取锁就是可重入锁。<br>反之，获取锁后，再次请求这个锁，无法获取到锁就是不可重入锁。</p>
<ul>
<li>可中断锁</li>
</ul>
<p>这个待完善。</p>
<h3 id="常用锁的原理分析"><a href="#常用锁的原理分析" class="headerlink" title="常用锁的原理分析"></a>常用锁的原理分析</h3><ul>
<li>ReentrantLock</li>
</ul>
<p>可重入锁，独占式的，默认是非公平锁，可通过构造方法来决定是公平锁还是非公平锁。</p>
<p>调用 lock 方法去尝试获取锁。</p>
<p>调用 unlock 方法释放锁。</p>
<ul>
<li>CountDownLatch</li>
</ul>
<p><code>await</code> 方法，调用此方法的时候，只有当 state 为 0 的时候才不阻塞，state 为其他值的情况下会阻塞线程</p>
<p>CountDownLatch 构造方法需要指定 count , 也就是 state</p>
<p><code>countDown</code> 方法，会使 count - 1 ，其实就是 count ，当  count - 1 == 0 的时候唤醒阻塞的线程。</p>
<p>适用于事情开始前，一些条件达成(条件达成，计数器减一)，然后继续。</p>
<p>需要注意的是 count 只有减少的方法，没有增加和重置的方法，故不可复用。</p>
<ul>
<li>CyclicBarrier </li>
</ul>
<p>强调的是，事情做完后，等其他线程也达到同等条件，然后在继续执行。</p>
<p>适用于事情做完后，等待某一条件达成，然后继续。</p>
<ul>
<li>ReentrantReadWriteLock</li>
</ul>
<p>里面包含读锁和写锁。读读不互斥，读写，写写互斥。就是两个线程都读数据的时候，不会阻塞，两个或者多个线程读写或者写写的时候会阻塞线程。</p>
<p>相对其他的锁，锁的粒度更小，效率会高一些，同样的，实现会复杂些。</p>
<p>默认是非公平锁，同样可以通过构造方法控制是否为公平锁。</p>
<p>read 锁为共享锁</p>
<p>write 锁为独占锁</p>
<p>这两个锁共用一个 AQS 框架的 state , state 高16位表示共享锁的 state , 低 16 为表示 write 锁的 state</p>
<ul>
<li>AQS 框架小结</li>
</ul>
<p>上面的四种框架很好的利用了 AQS 框架，重点基本在 <code>tryAcquire</code>、<code>tryAcquireShare</code> 里面，这 2 个方法的返回值是子类控制AQS框架是否阻塞线程的入口，如果需要自定义一种锁的话，需要好好设计这两个方法。 ReentrantReadWriteLock 就是一个很好的例子。</p>
<h2 id="线程间通信"><a href="#线程间通信" class="headerlink" title="线程间通信"></a>线程间通信</h2><p>这种互相通信的过程就是线程间的协作</p>
<p>多线程之间通讯，其实就是多个线程在操作同一个资源，但是操作的动作不同</p>
<p>线程间通信方式</p>
<ol>
<li>wait/notify </li>
</ol>
<p>synchornized 的时候，通过 wait/notify 来暂停线程和通知线程，从而达到通信的目的。</p>
<pre><code class="java">Object 类的方法，final 的，表示子类不可修改
wait(long time)  主动释放锁，然后休眠，在指定的时间长度后自动唤醒或者被系统唤醒。
notify() 随机唤醒一个等待的线程进入就绪队列
notifyAll() 唤醒所有等待的线程进入就绪队列
</code></pre>
<p>参考资料</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/u011635492/article/details/83043212">JAVA线程通信详解</a></p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/bohu83/article/details/51098106">java condition使用及分析</a></p>
<ol start="2">
<li>lock/condition</li>
</ol>
<p>这个其实和 wait/notify  类似，不过这个是语言层面实现的，不是虚拟机层面的实现。</p>
<ol start="3">
<li>管道 </li>
</ol>
<p>PipedInputStream/PipedOutputStream 来实现的，一个是开始，一个是结束。</p>
<p>Object 和 Thread 常用方法介绍</p>
<pre><code class="java">Object: 下面的方法都只能在同步块中调用

wait()  释放锁资源，并等待唤醒

wait(long time)  释放锁资源，并在指定事件后唤醒

notify()  随机唤醒一个线程进入就绪列表

notifyAll() 唤醒所有线程进入就绪列表
</code></pre>
<pre><code class="java">Thread: 类方法

sleep(long time) 让线程休眠指定事件，但是不释放锁资源。

join() 等待目标线程结束
</code></pre>
<h2 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h2><p>通过 ThreadPoolExcutor 类来创建线程池。</p>
<p>创建线程池 5 个参数的含义</p>
<table>
<thead>
<tr>
<th>参数</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>corePoolSize</td>
<td>线程池的基本大小，即在没有任务需要执行的时候线程池的大小，并且只有在工作队列满了的情况下才会创建超出这个数量的线程</td>
</tr>
<tr>
<td>maximumPoolSize</td>
<td>线程池中允许的最大线程数，只有工作队列满了，才可能继续创建线程，但是同时运行的线程数不会超过这个</td>
</tr>
<tr>
<td>keepAliveTime</td>
<td>当 idle 的线程数大于 corePoolSize 时，idle 的线程可以存活的时间。</td>
</tr>
<tr>
<td>unit</td>
<td>时间单位</td>
</tr>
<tr>
<td>workQueue</td>
<td>没有被执行的任务会放到这个队列里面</td>
</tr>
<tr>
<td>threadFactory</td>
<td>用来创建新的线程的</td>
</tr>
<tr>
<td>handler</td>
<td></td>
</tr>
</tbody></table>
<p>参考资料</p>
<p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/frankyou/p/10135212.html">理解ThreadPoolExecutor线程池的corePoolSize、maximumPoolSize和poolSize</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.im/post/6844903909178212359">探索 Android 多线程优化方法</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.im/post/6855586076132655118">一次Android线程优化的探索</a></p>

  
  
    
    <div class='footer'>
      
      
      
        <div class='copyright'>
          <blockquote>
            
              
                <p>本文永久链接是：<a href=http://xander_wang.gitee.io/android-note/2021/02/26/android_note/android_note_05/>http://xander_wang.gitee.io/android-note/2021/02/26/android_note/android_note_05/</a></p>
              
            
          </blockquote>
        </div>
      
      
    </div>
  
  
    


  <div class='article-meta' id="bottom">
    <div class='new-meta-box'>
      
        
          
<div class='new-meta-item author'>
  <a class='author' target="_blank" href="https://github.com/XanderWang/" rel="nofollow noopener">
    <img no-lazy src="https://i.loli.net/2020/05/18/WO1oJwFsRb4gV79.png">
    <p>XanderWang</p>
  </a>
</div>

        
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2022-12-11T10:26:22+00:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：Dec 11, 2022</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/android-note/tags/Android/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>Android</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/android-note/tags/%E7%BA%BF%E7%A8%8B/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>线程</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://xander_wang.gitee.io/android-note/2021/02/26/android_note/android_note_05/&title=Android 开发总结笔记(五) - Java 线程总结 - Xander's blog&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" class="lazyload placeholder" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@3/img/placeholder/c617bfd2497fcea598e621413e315c368f8d8e.svg">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=http://xander_wang.gitee.io/android-note/2021/02/26/android_note/android_note_05/&title=Android 开发总结笔记(五) - Java 线程总结 - Xander's blog&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" class="lazyload placeholder" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@3/img/placeholder/c617bfd2497fcea598e621413e315c368f8d8e.svg">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://service.weibo.com/share/share.php?url=http://xander_wang.gitee.io/android-note/2021/02/26/android_note/android_note_05/&title=Android 开发总结笔记(五) - Java 线程总结 - Xander's blog&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" class="lazyload placeholder" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@3/img/placeholder/c617bfd2497fcea598e621413e315c368f8d8e.svg">
          
        </a>
      
    
      
        
        <div class='hoverbox'>
          <a class='share'><img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/wechat.png" class="lazyload placeholder" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/wechat.png" srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@3/img/placeholder/c617bfd2497fcea598e621413e315c368f8d8e.svg"></a>
          <div class='target'>
            <img src="">
          </div>
        </div>
      
    
      
    
  </div>
</div>



        
      
    </div>
  </div>


  
  

  
    <div class="prev-next">
      
        <a class='prev' href='/android-note/2021/02/26/android_note/android_note_06/'>
          <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>Android 开发总结笔记(六) - 网络编程总结</p>
          <p class='content'>网络编程总结网络协议总览网络协议分层
网络协议框架
各层协议之间的区别合联系应用层: Http WebSocket FTP 等
传输层: TCP UDP
网络层: IP
链路层: -


TCP...</p>
        </a>
      
      
        <a class='next' href='/android-note/2021/02/26/android_note/android_note_04/'>
          <p class='title'>Android 开发总结笔记(四) - JVM 总结<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
          <p class='content'>JVM 总结什么是 JVMJVM 是 Java 虚拟机，是一个虚拟出来的计算机，仿真模拟计算机。
JVM 在运行程序的时候，这个程序在 JVM 里面是怎么样的？JVM 的内存主要分为五块

程序...</p>
        </a>
      
    </div>
  
</article>


  

  <article class="post white-box reveal shadow" id="comments">
    <p ct><i class='fas fa-comments'></i> 评论</p>
    
    <div id="valine_container" class="valine_thread">
  <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
</div>

  </article>






</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper shadow desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Java-%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8"><span class="toc-text">Java 线程安全</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8"><span class="toc-text">什么是线程安全</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Volatile"><span class="toc-text">Volatile</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Java-%E5%8F%98%E9%87%8F%E7%9A%84%E8%AF%BB%E5%86%99"><span class="toc-text">Java 变量的读写</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#volatile-%E5%A6%82%E4%BD%95%E4%BF%9D%E6%8C%81%E5%86%85%E5%AD%98%E5%8F%AF%E8%A7%81%E6%80%A7"><span class="toc-text">volatile 如何保持内存可见性</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#volatile-%E5%A6%82%E4%BD%95%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F"><span class="toc-text">volatile 如何防止指令重排序</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%96%B9%E5%BC%8F"><span class="toc-text">线程安全的实现方式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#synchronized"><span class="toc-text">synchronized</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%94%81%E8%86%A8%E8%83%80%E8%BF%87%E7%A8%8B"><span class="toc-text">锁膨胀过程</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Lock-volatile"><span class="toc-text">Lock + volatile</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Java-%E9%87%8C%E9%94%81%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-text">Java 里锁的分类</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B8%B8%E7%94%A8%E9%94%81%E7%9A%84%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90"><span class="toc-text">常用锁的原理分析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1"><span class="toc-text">线程间通信</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-text">线程池</span></a></li></ol>
    </div>
  </section>


  


</aside>



		  
		  <!--此文件用来存放一些不方便取值的变量-->
<!--思路大概是将值藏到重加载的区域内-->

<script>
  window.pdata={}
  pdata.ispage=true;
  pdata.postTitle="Android 开发总结笔记(五) - Java 线程总结";
  pdata.commentPath="";
  pdata.commentPlaceholder="";
  // header 这里无论是否开启pjax都需要
  var l_header=document.getElementById("l_header");
  
  l_header.classList.add("show");
  
  
    // cover
    var cover_wrapper=document.querySelector('.cover-wrapper');
    
    cover_wrapper.id="none";
    cover_wrapper.style.display="none";
    
  
</script>

        </div>
        
  
  <footer class="footer clearfix">
    <br><br>
    
      
        <div><p>Blog content follows the <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en">Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) License</a></p>
</div>
      
    
      
        
          <div><p><span id="lc-sv">本站总访问量为 <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 次</span> <span id="lc-uv">访客数为 <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span> 人</span></p>
</div>
        
      
    
      
        Use
        <a href="https://github.com/volantis-x/hexo-theme-volantis/tree/4.3.1" target="_blank" class="codename">Volantis</a>
        as theme, total visits
          <span id="busuanzi_value_site_pv"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
          times
        
      
    
      
        <div class='copyright'>
        <p><a href="/">Copyright © 2017-2020 XXX</a></p>

        </div>
      
    
      
        
      
    
  </footer>


        <a id="s-top" class="fas fa-arrow-up fa-fw" href="javascript:void(0)"></a>
      </div>
    </div>
    <div>
      <script>
/************这个文件存放不需要重载的全局变量和全局函数*********/
window.volantis={};
window.volantis.loadcss=document.getElementById("loadcss");
/******************** Pjax ********************************/
function VPjax(){
	this.list=[] // 存放回调函数
	this.start=()=>{
	  for(var i=0;i<this.list.length;i++){
		this.list[i].run();
	  }
	}
	this.push=(fn,name)=>{
		var f=new PjaxItem(fn,name);
		this.list.push(f);
	}
	// 构造一个可以run的对象
	function PjaxItem(fn,name){
		// 函数名称
		this.name = name || fn.name
		// run方法
		this.run=()=>{
			fn()
		}
	}
}
volantis.pjax={}
volantis.pjax.method={
	complete: new VPjax(),
	error: new VPjax(),
	send: new VPjax()
}
volantis.pjax={
	...volantis.pjax,
	push: volantis.pjax.method.complete.push,
	error: volantis.pjax.method.error.push,
	send: volantis.pjax.method.send.push
}
/********************脚本懒加载函数********************************/
// 已经加入了setTimeout
function loadScript(src, cb) {
	setTimeout(function() {
		var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
		var script = document.createElement('script');
		script.setAttribute('type','text/javascript');
		if (cb) script.onload = cb;
		script.setAttribute('src', src);
		HEAD.appendChild(script);
	});
}
//https://github.com/filamentgroup/loadCSS
var loadCSS = function( href, before, media, attributes ){
	var doc = window.document;
	var ss = doc.createElement( "link" );
	var ref;
	if( before ){
		ref = before;
	}
	else {
		var refs = ( doc.body || doc.getElementsByTagName( "head" )[ 0 ] ).childNodes;
		ref = refs[ refs.length - 1];
	}
	var sheets = doc.styleSheets;
	if( attributes ){
		for( var attributeName in attributes ){
			if( attributes.hasOwnProperty( attributeName ) ){
				ss.setAttribute( attributeName, attributes[attributeName] );
			}
		}
	}
	ss.rel = "stylesheet";
	ss.href = href;
	ss.media = "only x";
	function ready( cb ){
		if( doc.body ){
			return cb();
		}
		setTimeout(function(){
			ready( cb );
		});
	}
	ready( function(){
		ref.parentNode.insertBefore( ss, ( before ? ref : ref.nextSibling ) );
	});
	var onloadcssdefined = function( cb ){
		var resolvedHref = ss.href;
		var i = sheets.length;
		while( i-- ){
			if( sheets[ i ].href === resolvedHref ){
				return cb();
			}
		}
		setTimeout(function() {
			onloadcssdefined( cb );
		});
	};
	function loadCB(){
		if( ss.addEventListener ){
			ss.removeEventListener( "load", loadCB );
		}
		ss.media = media || "all";
	}
	if( ss.addEventListener ){
		ss.addEventListener( "load", loadCB);
	}
	ss.onloadcssdefined = onloadcssdefined;
	onloadcssdefined( loadCB );
	return ss;
};
</script>
<script>
  
  loadCSS("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css", window.volantis.loadcss);
  
  
  loadCSS("https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css", window.volantis.loadcss);
  
  
  loadCSS("https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css", window.volantis.loadcss);
  
  
</script>
<!-- required -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script>

<script>
  function pjax_fancybox() {
    $(".md .gallery").find("img").each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("class", "fancybox");
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 判断当前页面是否存在描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".md .gallery").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  function SCload_fancybox() {
    if ($(".md .gallery").find("img").length == 0) return;
    loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css", document.getElementById("loadcss"));
    loadScript('https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js', pjax_fancybox)
  };
  $(function () {
    SCload_fancybox();
  });
  function Pjax_SCload_fancybox(){
	if (typeof $.fancybox == "undefined") {
	 SCload_fancybox();
    } else {
	 pjax_fancybox();
    }
  }
  volantis.pjax.push(Pjax_SCload_fancybox)
  volantis.pjax.send(()=>{
      if (typeof $.fancybox != "undefined") {
        $.fancybox.close();    // 关闭弹窗
      }
  },'fancybox')
</script>


<!-- internal -->

  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
        var imgs=["https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/001.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/002.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/003.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/004.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/005.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/006.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/012.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/016.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/019.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/025.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/033.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/034.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/035.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/038.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/039.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/042.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/046.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/051.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/052.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/054.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/056.jpg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
	  function Pjax_backstretch(){
        
          $('#cover-backstretch').backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        
	  }
	  loadScript("https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js",Pjax_backstretch)
    </script>
  




<script>
  function loadIssuesJS() {
    if ($(".md").find(".issues-api").length == 0) return;
	
	  loadScript('/android-note/js/issues.js');
	
  };
  $(function () {
    loadIssuesJS();
  });
  volantis.pjax.push(()=>{
	if (typeof IssuesAPI == "undefined") {
	  loadIssuesJS();
	}
  },"IssuesJS")
</script>



  <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>




  

<script>
  window.FPConfig = {
	delay: 0,
	ignoreKeywords: [],
	maxRPS: 5,
	hoverDelay: 25
  };
</script>
<script defer src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script>





  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
    var clipboard = new ClipboardJS('.btn-copy', {
        target: function (trigger) {
            return trigger.nextElementSibling
        }
    });
    function wait(callback, seconds) {
        var timelag = null;
        timelag = window.setTimeout(callback, seconds)
    }
    function pjax_initCopyCode() {
		if($(".highlight .code pre").length+$(".article pre code").length==0)return;
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        $(".article pre code").before(copyHtml);
        clipboard.off('success').on('success', function (e) {
            let $btn = $(e.trigger);
            $btn.addClass('copied');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-check-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPIED';
            wait(function () {
                $icon.removeClass('fa-check-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        });
        clipboard.off('error').on('error', function (e) {
            e.clearSelection();
            let $btn = $(e.trigger);
            $btn.addClass('copy-failed');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-times-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPY FAILED';
            wait(function () {
                $icon.removeClass('fa-times-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        })
    }
    $(function () {
        pjax_initCopyCode()
    });
	volantis.pjax.push(pjax_initCopyCode)
</script>




   <script type="text/javascript">
  loadScript("https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js")
  function pjax_scrollrebeal() {
    ScrollReveal().reveal('.l_main .reveal', {
      distance: '32px',
      duration: '800',
      interval: '20',
      scale: '1',
      easing: 'ease-out'
    });
  }
  $(function () {
  var checkScrollReveal = setInterval(function () {
    if ($("#safearea").css("display")!="block") return
    if (typeof ScrollReveal=="undefined") return
    clearInterval(checkScrollReveal)
	pjax_scrollrebeal();
  }, 100)
  });
  volantis.pjax.push(pjax_scrollrebeal)
</script>






  
  
<script src="https://cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js"></script>


<script>
  function emoji(path, idx, ext) {
    return path + "/" + path + "-" + idx + "." + ext;
  }
  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }
  function pjax_valine() {
    if(!document.querySelectorAll("#valine_container")[0])return;
    let pagePlaceholder = pdata.commentPlaceholder || "快来评论吧~";
    let path = pdata.commentPath;
    if (path.length == 0) {
      let defaultPath = '';
      path = defaultPath || decodeURI(window.location.pathname);
    }
    var valine = new Valine();
    valine.init(Object.assign({"path":null,"placeholder":"快来评论吧~","appId":"rFjxhNkjfJEFwCxatct9lFP5-gzGzoHsz","appKey":"bPYEsXC56n2ziDYGE5pg7EHW","meta":["nick","mail"],"requiredFields":["nick"],"enableQQ":true,"recordIP":false,"avatar":"robohash","pageSize":10,"lang":"zh-cn","highlight":true,"mathJax":false,"js":"https://cdn.jsdelivr.net/npm/valine@1.4/dist/Valine.min.js"}, {
      el: '#valine_container',
      path: path,
      placeholder: pagePlaceholder,
      emojiCDN: 'https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/',
      emojiMaps: emojiMaps,
    }))
  }
  $(function () {
    pjax_valine();
  });
  volantis.pjax.push(pjax_valine);
</script>




  <script defer src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js" data-pjax></script>



  
<script src="/android-note/js/app.js"></script>



<!-- optional -->

  <script>
const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/";
const ROOT =  ("/android-note/" || "/").endsWith('/') ? ("/android-note/" || "/") : ("/android-note//" || "/" );

$('.input.u-search-input').one('focus',function(){
	
		loadScript('/android-note/js/search/hexo.js',setSearchService);
	
})

function listenSearch(){
  
    customSearch = new HexoSearch({
      imagePath: SearchServiceimagePath
    });
  
}
function setSearchService() {
	listenSearch();
	
}
</script>





  
<script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>

<script type="text/javascript">
$(function () {
  Waves.attach('.flat-btn', ['waves-button']);
  Waves.attach('.float-btn', ['waves-button', 'waves-float']);
  Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
  Waves.attach('.flat-box', ['waves-block']);
  Waves.attach('.float-box', ['waves-block', 'waves-float']);
  Waves.attach('.waves-image');
  Waves.init();
});
</script>



  
<script src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2/js/comment_typing.js"></script>






  <script defer>

  const LCCounter = {
    app_id: 'rFjxhNkjfJEFwCxatct9lFP5-gzGzoHsz',
    app_key: 'bPYEsXC56n2ziDYGE5pg7EHW',
    custom_api_server: '',

    // 查询存储的记录
    getRecord(Counter, url, title) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({url})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {url, title: title, times: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    },

    // 发起自增请求
    increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    },

    // 构建自增请求体
    buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "times": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    },

    // 校验是否为有效的 UV
    validUV() {
      var key = 'LeanCloudUVTimestamp';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    },

    addCount(Counter) {
      var enableIncr = '' === 'true' && window.location.hostname !== 'localhost';
      enableIncr = true;
      var getterArr = [];
      var incrArr = [];
      // 请求 PV 并自增
      var pvCtn = document.querySelector('#lc-sv');
      if (pvCtn || enableIncr) {
        var pvGetter = this.getRecord(Counter, 'http://xander_wang.gitee.io/android-note' + '/#lc-sv', 'Visits').then((record) => {
          incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-sv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + 1;
              if (pvCtn) {
                pvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#lc-uv');
      if (uvCtn || enableIncr) {
        var uvGetter = this.getRecord(Counter, 'http://xander_wang.gitee.io/android-note' + '/#lc-uv', 'Visitors').then((record) => {
          var vuv = this.validUV();
          vuv && incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-uv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + (vuv ? 1 : 0);
              if (uvCtn) {
                uvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(uvGetter);
      }

      // 请求文章的浏览数，如果是当前页面就自增
      var allPV = document.querySelectorAll('#lc-pv');
      if (allPV.length > 0 || enableIncr) {
        for (i = 0; i < allPV.length; i++) {
          let pv = allPV[i];
          let title = pv.getAttribute('data-title');
          var url = 'http://xander_wang.gitee.io/android-note' + pv.getAttribute('data-path');
          if (url) {
            var viewGetter = this.getRecord(Counter, url, title).then((record) => {
              // 是当前页面就自增
              let curPath = window.location.pathname;
              if (curPath.includes('index.html')) {
                curPath = curPath.substring(0, curPath.lastIndexOf('index.html'));
              }
              if (pv.getAttribute('data-path') == curPath) {
                incrArr.push(this.buildIncrement(record.objectId));
              }
              if (pv) {
                var ele = pv.querySelector('#lc-pv #number');
                if (ele) {
                  if (pv.getAttribute('data-path') == curPath) {
                    ele.innerText = (record.times || 0) + 1;
                  } else {
                    ele.innerText = record.times || 0;
                  }
                  pv.style.display = 'inline';
                }
              }
            });
            getterArr.push(viewGetter);
          }
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && this.increment(Counter, incrArr);
        })
      }

    },


    fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': this.app_id,
            'X-LC-Key': this.app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      this.addCount(Counter);
    },

    refreshCounter() {
      var api_server = this.app_id.slice(-9) !== '-MdYXbMMI' ? this.custom_api_server : `https://${ this.app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;
      if (api_server) {
        this.fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + this.app_id)
          .then(resp => resp.json())
          .then(({api_server}) => {
            this.fetchData('https://' + api_server);
          });
      }
    }

  };

  LCCounter.refreshCounter();

  document.addEventListener('pjax:complete', function () {
    LCCounter.refreshCounter();
  });
</script>




  <script>
const rootElement = document.documentElement;
const darkModeStorageKey = "user-color-scheme";
const rootElementDarkModeAttributeName = "data-user-color-scheme";

const setLS = (k, v) => {
    localStorage.setItem(k, v);
};

const removeLS = (k) => {
    localStorage.removeItem(k);
};

const getLS = (k) => {
    return localStorage.getItem(k);
};

const getModeFromCSSMediaQuery = () => {
  return window.matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
};

const resetRootDarkModeAttributeAndLS = () => {
  rootElement.removeAttribute(rootElementDarkModeAttributeName);
  removeLS(darkModeStorageKey);
};

const validColorModeKeys = {
  dark: true,
  light: true,
};

const applyCustomDarkModeSettings = (mode) => {
  const currentSetting = mode || getLS(darkModeStorageKey);

  if (currentSetting === getModeFromCSSMediaQuery()) {
    resetRootDarkModeAttributeAndLS();
  } else if (validColorModeKeys[currentSetting]) {
    rootElement.setAttribute(rootElementDarkModeAttributeName, currentSetting);
  } else {
    resetRootDarkModeAttributeAndLS();
  }
};

const invertDarkModeObj = {
  dark: "light",
  light: "dark",
};

/**
 * get target mode
 */
const toggleCustomDarkMode = () => {
  let currentSetting = getLS(darkModeStorageKey);

  if (validColorModeKeys[currentSetting]) {
    currentSetting = invertDarkModeObj[currentSetting];
  } else if (currentSetting === null) {
    currentSetting = invertDarkModeObj[getModeFromCSSMediaQuery()];
  } else {
    return;
  }
  setLS(darkModeStorageKey, currentSetting);
  return currentSetting;
};

/**
 * bind click event for toggle button
 */
var btn=$("#wrapper .toggle-mode-btn,#rightmenu-wrapper .toggle-mode-btn");
function bindToggleButton() {
    btn.on('click',(e) => {
      const mode = toggleCustomDarkMode();
      applyCustomDarkModeSettings(mode);
    });
}

applyCustomDarkModeSettings();
document.addEventListener("DOMContentLoaded", bindToggleButton);
volantis.pjax.push(bindToggleButton);
volantis.pjax.send(()=>{
	btn.unbind('click');
},'toggle-mode-btn-unbind');
</script>








<script>
function listennSidebarTOC() {
  const navItems = document.querySelectorAll(".toc li");
  if (!navItems.length) return;
  const sections = [...navItems].map((element) => {
    const link = element.querySelector(".toc-link");
    const target = document.getElementById(
      decodeURI(link.getAttribute("href")).replace("#", "")
    );
    link.addEventListener("click", (event) => {
      event.preventDefault();
      window.scrollTo({
		top: target.offsetTop + 100,
		
		behavior: "smooth"
		
	  });
    });
    return target;
  });

  function activateNavByIndex(target) {
    if (target.classList.contains("active-current")) return;

    document.querySelectorAll(".toc .active").forEach((element) => {
      element.classList.remove("active", "active-current");
    });
    target.classList.add("active", "active-current");
    let parent = target.parentNode;
    while (!parent.matches(".toc")) {
      if (parent.matches("li")) parent.classList.add("active");
      parent = parent.parentNode;
    }
  }

  function findIndex(entries) {
    let index = 0;
    let entry = entries[index];
    if (entry.boundingClientRect.top > 0) {
      index = sections.indexOf(entry.target);
      return index === 0 ? 0 : index - 1;
    }
    for (; index < entries.length; index++) {
      if (entries[index].boundingClientRect.top <= 0) {
        entry = entries[index];
      } else {
        return sections.indexOf(entry.target);
      }
    }
    return sections.indexOf(entry.target);
  }

  function createIntersectionObserver(marginTop) {
    marginTop = Math.floor(marginTop + 10000);
    let intersectionObserver = new IntersectionObserver(
      (entries, observe) => {
        let scrollHeight = document.documentElement.scrollHeight + 100;
        if (scrollHeight > marginTop) {
          observe.disconnect();
          createIntersectionObserver(scrollHeight);
          return;
        }
        let index = findIndex(entries);
        activateNavByIndex(navItems[index]);
      },
      {
        rootMargin: marginTop + "px 0px -100% 0px",
        threshold: 0,
      }
    );
    sections.forEach((element) => {
      element && intersectionObserver.observe(element);
    });
  }
  createIntersectionObserver(document.documentElement.scrollHeight);
}

document.addEventListener("DOMContentLoaded", listennSidebarTOC);
document.addEventListener("pjax:success", listennSidebarTOC);
</script>

<!-- more -->

 
	   
	    


<script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script>


<script>
    var pjax;
    document.addEventListener('DOMContentLoaded', function () {
      pjax = new Pjax({
        elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',
        selectors: [
          "title",
          
          "#pjax-container",
          "#pjax-header-nav-list"
        ],
        cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
        timeout: 5000
      });
    });

    document.addEventListener('pjax:send', function (e) {
      //window.stop(); // 相当于点击了浏览器的停止按钮

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      window.subData = null; // 移除标题（用于一二级导航栏切换处）

      volantis.$switcher.removeClass('active'); // 关闭移动端激活的搜索框
      volantis.$header.removeClass('z_search-open'); // 关闭移动端激活的搜索框
      volantis.$wrapper.removeClass('sub'); // 跳转页面时关闭二级导航

      // 解绑事件 避免重复监听
      volantis.$topBtn.unbind('click');
      $('.menu a').unbind('click');
      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');
	  // 使用 volantis.pjax.send 方法传入pjax:send回调函数 参见layout/_partial/scripts/global.ejs
	  volantis.pjax.method.send.start();
    });

    document.addEventListener('pjax:complete', function () {
      $('.nav-main').find('.list-v').not('.menu-phone').removeAttr("style",""); // 移除小尾巴的移除
      $('.menu-phone.list-v').removeAttr("style",""); // 移除小尾巴的移除
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
      try{
		// 使用 volantis.pjax.push 方法传入重载函数 参见layout/_partial/scripts/global.ejs
		volantis.pjax.method.complete.start();
      } catch (e) {
        console.log(e);
      }
    });

    document.addEventListener('pjax:error', function (e) {
	  // 使用 volantis.pjax.error 方法传入pjax:error回调函数 参见layout/_partial/scripts/global.ejs
	  volantis.pjax.method.error.start();
      window.location.href = e.triggerElement.href;
    });
</script>
 
	  
    </div>
  </body>
</html>
